package com.blackhorse.simple;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

//消息生成者
public class Producer {
    public static final String QUEUE_NAME = "simple_queue";

    public static void main(String[] args) {
        //创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        //rabbitmq服务ip地址和端口，默认为localhost
        connectionFactory.setHost("192.168.81.130");
        connectionFactory.setPort(5672);
        //rabbitmq服务虚拟主机名：默认为/
        connectionFactory.setVirtualHost("/blackhorse");
        //用户名，默认guest
        connectionFactory.setUsername("root");
        //密码，默认guest
        connectionFactory.setPassword("root");
        Connection connection = null;
        Channel channel = null;
        try {
            //获取连接
            connection = connectionFactory.newConnection();
            //创建频道
            channel = connection.createChannel();

            //声明（创建）队列
            channel.queueDeclare(QUEUE_NAME,//队列名称
                    true, //是否定义持久化队列
                    false, //是否独占本次连接
                    false //是否在不使用的时候自动删除队列
                    , null); //队列其他参数
            //要发送的消息
            String message = "你好啊！！！！";
            channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
            System.out.println("发送消息：" + message);


        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        } finally {
            //释放资源
            try {
                if (channel != null) {
                    channel.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (TimeoutException e) {
                e.printStackTrace();
            }
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
